#include "socket_gather.h"

#include "socket_private_acl.h"
#include "socket_service.h"
#include "socket_gather_read.h"
#include "socket_gather_write.h"
#include "business_def.h"
#include "Log.h"
////////////////////////////////////////////////*MySocketExx*///////////////////////////////////////////////////////////////

SocketGather::SocketGather(int gid)
	: GatherChannel(gid)
{
	try {
		//
		if(ptr_BDef->getNetInfoByGID(gid,m_NetArg))
		{
			;
		}
		socket_acl = new SocketPrivate_ACL(this->port(),this->ip_addr());
		if (socket_acl->onConnect() > 0)
		{
			socket_srv = new SocketService();
			socket_srv->setPDataPtr(socket_acl);
			socket_srv->start();

			
			socket_read = new SocketGahterRead(this->type(), socket_acl, this);
			socket_read->start();

			socket_write = new SocketGatherWrite(this->type(), socket_acl, this);
			socket_write->start();

		}
		else {
			socket_srv = NULL;
			socket_read = NULL;
			socket_write = NULL;
			CLogger::createInstance()->Log(MsgError,
				"listen port(%d) error, [%s %s %d]"
				, this->port()
				, __FILE__, __FUNCTION__, __LINE__);
		}
	}
	catch (...) {
		delete socket_read;
		socket_read = NULL;
		delete socket_write;
		socket_write = NULL;
		delete socket_srv;
		socket_srv = NULL;
		delete socket_acl;
		socket_acl = NULL;

		CLogger::createInstance()->Log(MsgError,
			"SocketGather init error, [%s %s %d]"
			, __FILE__, __FUNCTION__, __LINE__);
	}
};

SocketGather::~SocketGather(void)
{
	if (NULL != socket_read) 
	{
		delete socket_read;
		socket_read = NULL;
	}
	if (NULL != socket_write) 
	{
		delete socket_write;
		socket_write = NULL;
	}

	if (NULL != socket_srv) 
	{
		delete socket_srv;
		socket_srv = NULL;
	}
	
	if(NULL!=socket_acl)
	{
		delete socket_acl;
		socket_acl = NULL;
	}
};

int SocketGather::Write(const char* buf, int size)
{
	if (NULL != socket_acl) 
	{
		return socket_acl->Write(buf, size);
	}
	else {
		return -1;
	}
}

////////////////////////////////////////////////////////
int SocketGather::getBuffer(unsigned long &ipInt, unsigned char* _buf)
{
	ChannelCmd it;
	if(!WriteDatas->pop(it)){
		return 0;
	}
	ipInt = it.flag;
	// printf("getBuffer:\n");
	// for (int j = 0; j < it.len; j++) {
	// 	printf("%02X", static_cast<unsigned char>(it.Buf[j]));
	// }
	// printf("\n");
	int nlen = 0;
	switch (m_NetArg.type)
	{
		case 1:
		{
			nlen = pyfree::code((unsigned char*)it.Buf, it.len, _buf);
		}
		break;
		// case 2:
		// {
		// 	memcpy(_buf,it.Buf,it.len);
		// }
		// break;
		default:
		{
			memcpy(_buf,it.Buf,it.len);
			nlen = it.len;
		}
		break;
	}
	return nlen;
}

int SocketGather::AddFrame(unsigned long link, const unsigned char *buf, int len)
{
	switch (m_NetArg.type)
	{
        case 1:
        {
            //反序列化
            unsigned char * pBuf = new unsigned char[len];
            int nLen = pyfree::uncode(buf, len, pBuf);
            msgResponse(pBuf, nLen,link);
            delete[] pBuf;
            pBuf = NULL;
        }
        break;
        // case 2://单帧,ascii
        // {
        //     msgResponse((unsigned char *)buf, len,link);
        // }
        // break;
        default:
		{
            msgResponse((unsigned char *)buf, len,link);
        }
            break;
	}
	return 1;
};

void SocketGather::msgResponse(unsigned char *buf, int len, unsigned long dev_addr)
{
	char _buf[512] = { 0 };
#ifdef DEBUG
	printf("msgResponse len(%d) from(%lu):\n", len,dev_addr);
	for (int i = 0; i < len; i++)
	{
		printf("%02X", buf[i]);
	}
	printf("\n");
#endif
	int rlen = pyfree::bytes2string(buf, _buf, len);//ascii to hex
	std::string atres = std::string((char*)_buf);
	std::string _otherDesc = "";
	rlen+=1;
	if(protodefs.oldState>0)//脚本解析需要下发指令
	{
		char d_buf[512] = { 0 };
		int dlen = pyfree::bytes2string((unsigned char *)cstate.newcmd.c_str()
			, d_buf, static_cast<int>(cstate.newcmd.length()));//control cmd,ascii to hex
		_otherDesc = std::string((char*)d_buf, dlen);
	}
	unsigned long _taskID = cstate.taskID;
	if (_taskID <= 0) 
	{
		_taskID = pyfree::getTaskIDFromDateTime(0);//无下控任务ID,创建新编号
	}
	msgAnalysis(atres,_otherDesc,_taskID,false,dev_addr);
	setValue(-3,1.0,_taskID,dev_addr);	//信道读取数据正常
}

////////////////////////////////////////////////////////////////
void SocketGather::downControl(int _exetype, int _type, int _pid, float _val, unsigned long _taskID)
{
	std::string _cmd = "";
	int checktype = 0;
	unsigned long iplong = 0;
	if (getCmd(_exetype, _type, _pid, _val, _cmd, checktype, iplong,_taskID))
	{
		// printf("downControl:\n");
		// for (unsigned int j = 0; j < _cmd.length(); j++) {
		// 	printf("%02X", static_cast<unsigned char>(_cmd.at(j)));
		// }
		// printf("\n");
		//级联时 需要指定连接地址下控,做到针对性
		ChannelCmd _wd((unsigned char*)_cmd.c_str(), static_cast<int>(_cmd.length()),true,_taskID,0,false,iplong);
		WriteDatas->add(_wd);
	}
	else {
		CLogger::createInstance()->Log(MsgWarn,
			"TaskID[%lu] and down_node[5-2] GatherChannel(%d,%s) downControl(%d,%d,%d,%.2f) getCmd fail. [%s %s %d]"
			, _taskID, gatheratts.id,gatheratts.name.c_str()
			, _exetype, _type, _pid, _val
			, __FILE__, __FUNCTION__, __LINE__);
	}
};

//////////////////////////////////////////////////////////
void SocketGather::TimeUp()
{
	this->TimeUpState();
}

void SocketGather::setLink(unsigned long ipInt, const bool flag)
{
	this->setValue(-1,flag?float(1): float(0),100089,ipInt);
}

std::string SocketGather::ip_addr()
{
	return m_NetArg.ip;
}

int SocketGather::port()
{
	return m_NetArg.port;
}

int SocketGather::type()
{
	return m_NetArg.type;
}

void SocketGather::add(ChannelCmd it)
{
	ReadDatas->add(it);
}

bool SocketGather::getFirst(ChannelCmd &it)
{
	return ReadDatas->getFirst(it);
}

bool SocketGather::removeFirst()
{
	return ReadDatas->removeFirst();
}

bool SocketGather::pop(ChannelCmd &it)
{
	return ReadDatas->pop(it);
}
